<?php

namespace JyWxThird\Kernel;

use GuzzleHttp\Client;

class Http
{
  private static $req;
  private static $headers = [];
  
  public static function asJson()
  {
    self::$headers['Content-Type'] = 'application/json;charset=UTF-8';
  }
  
  public static function httpGet(string $url, array $query = null, array $headers = null)
  {
    return self::request($url, 'GET', ['query' => $query, 'headers' => $headers]);
  }
  
  public static function httpPost(string $url, array $data = [], array $headers = [])
  {
    return self::request($url, 'POST', ['form_params' => $data, 'headers' => $headers]);
  }
  
  public static function httpPostRaw(string $url, string $data, array $headers = [], $returnJson = true)
  {
    if (!isset($headers['Content-Type'])) {
      $headers['Content-Type'] = 'application/json';
    }
    $options['http_errors'] = false;
    $client                 = new Client();
    self::$req              = $client->request('POST', $url, [
      'body'    => $data,
      'headers' => $headers,
    ]);
    return self::handleResponse(self::$req, $returnJson);
  }
  
  public static function httpPostJson(string $url, array $data = [], $query = null, $returnJson = true)
  {
    return self::request($url, 'POST', ['query' => $query, 'json' => $data], $returnJson);
  }
  
  public static function httpUpload(string $url, array $files = [], array $form = [], array $query = [])
  {
    $multipart = [];
    
    foreach ($files as $name => $path) {
      $filename    = pathinfo($path, PATHINFO_BASENAME);
      $multipart[] = [
        'name'     => $name,
        'contents' => file_exists($path) ? fopen($path, 'r') : '',
        'headers'  => [
          'Content-Disposition' => 'form-data; name="' . $name . '"; filename="' . $filename . '"',
        ],
      ];
    }
    foreach ($form as $name => $contents) {
      $multipart[] = compact('name', 'contents');
    }
    
    return self::request(
      $url,
      'POST',
      [
        'query'           => $query,
        'multipart'       => $multipart,
        'connect_timeout' => 60,
        'timeout'         => 60,
        'read_timeout'    => 60,
      ]
    );
  }
  
  public static function request($url, $method = 'GET', array $options = [], $returnJson = true)
  {
    $options['http_errors'] = false;
    
    // 协议头
    if (isset($options['headers'])) {
      $options['headers'] = array_merge(self::$headers, $options['headers']);
    } elseif (self::$headers) {
      $options['headers'] = self::$headers;
    }

    $client    = new Client();
    self::$req = $client->request($method, $url, $options);
    return self::handleResponse(self::$req, $returnJson);
  }
  
  public static function getHeaders()
  {
    return self::$req->getHeaders();
  }
  
  public static function getHeader($name)
  {
    return self::$req->getHeader($name);
  }
  
  public static function getCookies()
  {
    $temp    = self::$req->getHeader('Set-Cookie');
    $cookies = [];
    foreach ($temp as $v) {
      $temp1     = explode(';', $v);
      $cookies[] = $temp1[0];
    }
    return implode(';', $cookies);
  }
  
  public static function getStatusCode()
  {
    return self::$req->getStatusCode();
  }
  
  /**
   * 处理响应内容
   *
   * @param $request
   * @return mixed
   */
  public static function handleResponse($request, $returnJson)
  {
    $res = $request->getBody()->getContents();
    self::setHeaders([]);
    if ($returnJson && !is_null($temp = json_decode($res, true))) {
      return $temp;
    }
    return $res;
  }
  
  public static function setHeaders($headers)
  {
    self::$headers = $headers;
  }
}
